<?php

class RequestedUpdatesTask extends sfBaseTask
{
    protected function configure()
    {
        $this->addOptions(array(
            new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environement', 'prod'),
        ));
        
        $this->namespace = 'updates';
        $this->name = 'requested';
        $this->briefDescription = 'Run all pending requested updates';
        $this->detailedDescription = '';
    }
    
    protected function execute($arguments = array(), $options = array())
    {
        // Required to allow database queries
        $databaseManager = new sfDatabaseManager($this->configuration);
        
        LogHelper::log("Checking for pending runs.");
        
        $pendingRuns = Doctrine_Core::getTable('SourceRefreshRun')
                ->createQuery('srr')
                ->where('srr.requested_date IS NOT NULL')
                ->andWhere('srr.start_date IS NULL')
                ->orderBy('srr.requested_date')
                ->execute();
        foreach ($pendingRuns as $pendingRun) {
            LogHelper::log("Completing run " . $pendingRun->getId() . ".");
            
            $result = SourceUpdates::completeRun($pendingRun);
            
            LogHelper::log('Run ' . $pendingRun->getId() . ' finished. Attempted = ' . ($result['attempted'] ? 'true' : 'false') . ', already running = ' . ($result['alreadyRunning'] ? 'true' : 'false') . ', completed = ' . ($result['completed'] ? 'true' : 'false') . ', error = ' . ($result['error'] ? 'true' : 'false'));
        }
        
        LogHelper::log("Done.");
        echo "Done." . PHP_EOL;
    }
}